﻿using System;
using Csla;
using System.Collections.Generic;

namespace Sireass.Bl
{
    [Serializable]
    public class AsignacionList : ReadOnlyListBase<AsignacionList, AsignacionInfo>
    {
        #region Factory
        public static void GetAsignacionList(EventHandler<DataPortalResult<AsignacionList>> callback)
        {
            DataPortal.BeginFetch<AsignacionList>(callback);
        }

        public static AsignacionList GetAsignacionList()
        {
            return DataPortal.Fetch<AsignacionList>();
        }
        #endregion

        #region Métodos
        public static void AddObjectAuthorizationRules()
        {
            Type type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
            PerfilServicioCriteria criteria = new PerfilServicioCriteria(type.FullName, true);
            PerfilServicioList perfilesPorServicio = PerfilServicioList.GetPerfilServicioList(criteria);
            List<string> roles = new List<string>(perfilesPorServicio.Count);
            foreach (PerfilServicioInfo perfilServicio in perfilesPorServicio)
            {
                roles.Add(perfilServicio.Perfil);
            }

            Csla.Rules.BusinessRules.AddRule(type, new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.GetObject, roles));

        }
        #endregion

        #region Data Portal
        private void DataPortal_Fetch()
        {
            IsReadOnly = false;
            var rlce = RaiseListChangedEvents;
            RaiseListChangedEvents = false;

            using (var dalManager = Sireass.Dal.DalFactory.GetManager())
            {
                var dal = dalManager.GetProvider<Sireass.Dal.IAsignacionDal>();

                using (var data = dal.Fetch())
                {
                    while (data.Read())
                    {
                        var item = DataPortal.FetchChild<AsignacionInfo>(data);
                        Add(item);
                    }
                }
                RaiseListChangedEvents = rlce;
                IsReadOnly = true;
            }
        }
        #endregion
    }
}
